package main

import (
	"fmt"
	"sync"
	"time"
)

//并发读写测试
func main() {
	//testMapReadWriteDiffKey()
	testSyncMapReadWrite()
}

func testMapReadWriteDiffKey() {
	m := make(map[int]int)
	go func() {
		for {
			m[100] = 100
		}
	}()

	go func() {
		for {
			_ = m[12]
		}
	}()

	select {}

}

//map+读写锁
func testMapWithReadWriteLock() {
	var counter = struct {
		sync.Mutex
		m map[string]int
	}{m: make(map[string]int)}

	counter.Lock()
	i := counter.m["zz"]
	counter.Unlock()
	fmt.Printf("获取map的值 %d \n", i)
}

//使用sync.Map解决并发问题
func testSyncMapReadWrite() {
	m := sync.Map{}

	go func() {
		for i := 0; i < 1000; i++ {
			m.Store(i, i)
		}
	}()

	go func() {
		for j := 0; j < 1000; j++ {
			r, _ := m.Load(j)
			fmt.Printf("获取的数据 %d \n", r)
		}
	}()

	time.Sleep(time.Second * 1)

}
